package fun.tan90.easy.binlog.plugin.redis.cluster.config;


import com.github.benmanes.caffeine.cache.CacheLoader;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.model.OutputParam;
import fun.tan90.easy.binlog.plugin.redis.cluster.model.RedisClusterParams;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import lombok.extern.slf4j.Slf4j;
import org.noear.dami.Dami;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * description 动态连接mqtt
 * company 铁人科技
 *
 * @author Li YuLong
 * @date 2023/8/17 10:56
 */
@Slf4j
public class RedisClusterCacheLoader implements CacheLoader<String, JedisCluster> {

    @Override
    public @Nullable JedisCluster load(@NonNull String outputCode) throws Exception {
        OutputParam outputParam = Dami.<String, OutputParam>bus().sendAndRequest(DamiEventConstants.OUTPUT_PARAM_TOPIC, outputCode);
        if (Objects.isNull(outputParam)) {
            return null;
        }
        RedisClusterParams redisClusterParams = (RedisClusterParams) outputParam;
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisClusterParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisClusterParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisClusterParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisClusterParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间


        Set<HostAndPort> jedisClusterNodes = redisClusterParams.getNodes().stream().map(n -> new HostAndPort(n.getHost(), n.getPort())).collect(Collectors.toSet());
        int timeout = redisClusterParams.getTimeout();
        int maxAttempts = redisClusterParams.getMaxAttempts();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisClusterParams.getUser()) ? redisClusterParams.getUser() : null;
        String password = StringUtils.hasLength(redisClusterParams.getPassword()) ? redisClusterParams.getPassword() : null;
        return new JedisCluster(jedisClusterNodes, timeout, maxAttempts, soTimeout, user, password, "eb_redis_cluster", poolConfig);
    }
}